/*
 * @lc app=leetcode.cn id=1302 lang=cpp
 *
 * [1302] 层数最深叶子节点的和
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    void dfs(TreeNode *root, int depth, int &maxDepth, int &ans)
    {
        if (root == NULL)
            return;
        if (depth == maxDepth)
        {
            ans += root->val;
        }
        else if (depth > maxDepth)
        {
            maxDepth = depth;
            ans = root->val;
        }
        dfs(root->left, depth + 1, maxDepth, ans);
        dfs(root->right, depth + 1, maxDepth, ans);
    }
    int deepestLeavesSum(TreeNode *root)
    {
        int maxDepth = 0, ans = 0;
        dfs(root, 0, maxDepth, ans);
        return ans;
    }
};
// @lc code=end
